﻿using System;
using Castle.DynamicProxy;
using Castle.MonoRail.Framework;

namespace Yama.MVC.MonoRail.Extensions
{
    public class SelectActionInterceptor : IInterceptor
    {
        public static event ActionSelectedDelegate CurrentActionSelected;

        #region Implementation of IInterceptor

        public void Intercept(IInvocation invocation)
        {
            invocation.Proceed();

            if (invocation.Method.Name != "SelectAction" || CurrentActionSelected == null) return;

            var executableAction = (IExecutableAction)invocation.ReturnValue;

            CurrentActionSelected(this, new ActionSelectedDelegateArgs(executableAction));

            CurrentActionSelected = null;
        }

        #endregion
    }

    public delegate void ActionSelectedDelegate(object sender, ActionSelectedDelegateArgs args);

    public class ActionSelectedDelegateArgs : EventArgs
    {
        public ActionSelectedDelegateArgs(IExecutableAction executableAction)
        {
            this.SelectedAction = executableAction;
        }

        internal IExecutableAction SelectedAction { get; set; }
    }
}